<?php

class P2C_User_Action {

	var $initial = false;

	var $id;
	var $platform_id;
	var $project_id;
    var $date;
    var $ip;
    var $referral;
    
	public static function find( $args = '' ) {
        global $wpdb;
        
		$defaults = array(
			'post_status' => 'any',
			'posts_per_page' => -1,
			'offset' => 0,
			'orderby' => 'id',
			'order' => 'ASC' );

		$args = wp_parse_args( $args, $defaults );

		$user_actions = $wpdb->get_results("SELECT id, platform_id, project_id, ip, date, referral
            FROM p2c_user_action
            ORDER BY " . $args['orderby'] . " " . $args['order'] . " 
            LIMIT " . $args['offset'] . "," . $args['posts_per_page'] . ";");

		$objs = array();

		foreach ( $user_actions as $user_action )
			$objs[] = new self( $user_action );

		return $objs;
	}
    
    public static function rowcount( ) {
        global $wpdb;

		$user_actions = $wpdb->get_var("SELECT COUNT(*) FROM p2c_user_action;");
        
		return $user_actions;
	}

	public function __construct( $user_action = null ) {
        global $wpdb;
        
		$this->initial = true;
                
        if($user_action && !is_object($user_action)) {
            $user_action = $wpdb->get_row("SELECT id, platform_id, project_id, ip, date, referral FROM p2c_user_action WHERE id = " . (int) $user_action);
        }
        
		if ( $user_action ) {
			$this->initial = false;
			$this->id = $user_action->id;
			$this->platform_id = $user_action->platform_id;
			$this->project_id = $user_action->project_id;
			$this->ip = $user_action->ip;
            $this->date = $user_action->date;
            $this->referral = $user_action->referral;
		}
    }
    
	/* Save */

	function save() {
        global $wpdb; 
        
		if ( $this->initial ) {
			$wpdb->insert("p2c_user_action", array(
               "platform_id" => $this->platform_id,
               "project_id" => $this->project_id,
               "ip" => $this->ip,
               "date" => $this->date,
                "referral" => $this->referral
            ));
            
            $this->initial = false;
            $this->id = $wpdb->insert_id;
		} 

		return $this->id;
	}
    
    function parse() {
        
    }

}


?>